package com.zhentao.equipment;

import com.zhentao.equipment.mapper.SysOperationLogMapper;
import com.zhentao.pojo.SysOperationLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 简易审计切面：拦截equipment包下Controller写操作，记录操作日志
 */
@Aspect
@Component
public class AuditAspect {

    @Autowired
    private SysOperationLogMapper logMapper;

    @Around("execution(* com.zhentao.equipment.controller..*(..)) && (@annotation(org.springframework.web.bind.annotation.PostMapping) || @annotation(org.springframework.web.bind.annotation.PutMapping) || @annotation(org.springframework.web.bind.annotation.PatchMapping) || @annotation(org.springframework.web.bind.annotation.DeleteMapping))")
    public Object audit(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = null;
        int status = 1;
        try {
            result = pjp.proceed();
            return result;
        } catch (Throwable ex) {
            status = 2;
            throw ex;
        } finally {
            SysOperationLog log = new SysOperationLog();
            log.setUserId(null); // 可结合登录上下文设置
            log.setUsername(null);
            log.setOperationType(pjp.getSignature().getName());
            log.setOperationDesc(pjp.getSignature().toShortString());
            log.setRequestMethod(null);
            log.setRequestUrl(null);
            log.setIpAddress(null);
            log.setOperationTime(new Date());
            log.setStatus(status);
            logMapper.insert(log);
        }
    }
}





